package leetcode.editor.cn.q7xx

import leetcode.editor.cn.TreeNode
import java.util.*
import kotlin.math.abs
import kotlin.math.min

class Q783 {
    fun minDiffInBST(root: TreeNode): Int {
        val stack = Stack<TreeNode>()
        var curNode: TreeNode? = root
        var minDiff = Int.MAX_VALUE
        var prev: TreeNode? = null
        while (curNode!=null||!stack.empty()) {
            if (curNode != null) {
                stack.push(curNode)
                curNode = curNode.left
            } else {
                val temp = stack.pop()
                if (prev != null) {
                    minDiff = min(minDiff, abs(prev.`val`-temp.`val`))
                }
                prev = temp
                curNode = temp.right
            }
        }
        return minDiff
    }
}